package com.nsgf.library.domain.request;

import android.app.ProgressDialog;
import android.content.Context;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import retrofit2.HttpException;

/**
 * @ProjectName: gc
 * @Package: com.nsgf.library.domain.request
 * @ClassName: BaseHttpObserver
 * @Description: java类作用描述
 * @Author: 作者名
 * @CreateDate: 2024/11/6 15:10
 * @UpdateUser: 更新者：
 * @UpdateDate: 2024/11/6 15:10
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class BaseHttpObserver<T> extends io.reactivex.observers.DisposableObserver<T> {
    private ProgressDialog progressDialog;
    private HttpOnNextListener listener;
    private Context context;


    public BaseHttpObserver(HttpOnNextListener onNextListener) {
        this.listener = onNextListener;
    }

    @Override
    public void onNext(T t) {
        if (listener != null) {
            try {
                listener.onSuccess(t);
            } catch (Exception e) {
                e.printStackTrace();
                listener.onFail(e.getMessage());
            }
            dismissProgressDialog();
        }
    }


    @Override
    public void onError(Throwable e) {
        String error = null;
        try {

            if (e instanceof SocketTimeoutException) {//请求超时
                error = "请求超时";
            } else if (e instanceof ConnectException) {//网络连接超时
                error = "网络连接超时";
            } else if (e instanceof SSLHandshakeException) {//安全证书异常
                error = "安全证书异常";
            } else if (e instanceof HttpException) {//请求的地址不存在
                int code = ((HttpException) e).code();
                if (code == 504) {
                    error = "网络异常，请检查您的网络状态";
                } else if (code == 404) {
                    error = "请求的地址不存在";
                } else {
                    error = "请求失败";
                }
            } else if (e instanceof UnknownHostException) {//域名解析失败
                    error = "网络异常，请检查您的网络状态";
            } else {
                error = e.getMessage();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            dismissProgressDialog();
            progressDialog = null;
        }
        if (listener != null) {
            listener.onFail(error);
            dismissProgressDialog();
        }
    }

    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        progressDialog = null;
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
        listener.onComplete();
    }

}
